package com.direct.ratelimit.limit;

import java.util.Collection;

import com.direct.ratelimit.RateLimitRequest;

public class DefaultLimitService implements LimitService {

	private LimitDAO limitDAO = new InMemoryLimitDAO();

	public void setLimitDAO(LimitDAO limitDAO) {
		this.limitDAO = limitDAO;
	}

	@Override
	public Collection<Limit> getLimits(RateLimitRequest rateLimitRequest) {

		Collection<Limit> limits = limitDAO.getLimits(rateLimitRequest);
		Collection<ClientLimitOverride> clientLimitOverrides = limitDAO.getClientLimitOverrides(limits, rateLimitRequest.getClientId());

		return applyClientLimits(clientLimitOverrides, limits);
	}

	/**
	 * @param clientLimitOverrides
	 * @return
	 */
	protected Collection<Limit> applyClientLimits(Collection<ClientLimitOverride> clientLimitOverrides, Collection<Limit> limits) {

		for (Limit limit : limits) {
			// search for overrides and get them ready
			for (ClientLimitOverride clientLimitOverride : clientLimitOverrides) {
				if (clientLimitOverride.getLimitId().equals(limit.getId())) {
					limit.setRequestLimit(clientLimitOverride.getLimit());
				}
			}
		}

		return null;
	}

}
